package com.twu.biblioteca;


import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.concurrent.Callable;

public class LoginManager {
    private static ArrayList<Customer> listOfCustomers=new ArrayList<Customer>();
    private static Dictionary<Customer, String> registeredCustomers=new Hashtable<Customer, String>();
    ArrayList<Customer> loggedInCustomers;
    static {
        listOfCustomers.add(new Customer("Tina","tinam@houghtworks.com",783794596,"111-0000"));
        listOfCustomers.add(new Customer("Divya","uppudiv@houghtworks.com",783792396,"111-0001"));
        listOfCustomers.add(new Customer("Surya","surya@houghtworks.com",783794595,"111-0002"));
        listOfCustomers.add(new Customer("Pavan","pavan@houghtworks.com",783794579,"111-0003"));
        registeredCustomers.put(listOfCustomers.get(0),"tina@123");
        registeredCustomers.put(listOfCustomers.get(1),"div@123");
        registeredCustomers.put(listOfCustomers.get(2),"surya@123");
        registeredCustomers.put(listOfCustomers.get(3),"pavan@123");
    }

    LoginManager(){
        loggedInCustomers=new ArrayList<Customer>();
    }

    public Customer getCustomer(String libraryNo) throws Exception {
        for (Customer customer : listOfCustomers) {
            if (customer.getLibraryNo().equals(libraryNo))
                return customer;
        }
        throw new InvalidLibnoException();
    }

    public void login(String libraryNo, String password) throws Exception {
        Customer customer = getCustomer(libraryNo);
        if(password.equals(String.valueOf(registeredCustomers.get(customer)))) {
            loggedInCustomers.add(customer);
        }
        else
          throw new InvalidPasswordException();
    }

    public Customer getOnlineCustomer() throws Exception {
        if(loggedInCustomers.size()!=0)
            return loggedInCustomers.get(0);
        else
            throw new LoggedInException();
    }

    public void logout() throws Exception {
        if(loggedInCustomers.size()==1) {
            loggedInCustomers.remove(0);
        }
        else
            throw new OnlineCustomerException();
    }
}
